package com.haier.os.security.core.validate.code;

import com.haier.os.security.core.validate.code.image.ImageCode;
import com.haier.os.security.core.validate.code.sms.SmsCodeSender;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 验证码处理类
 */
@RestController
public class ValidateCodeController {
//    protected static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
//    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
//    @Autowired
//    private ValidateCodeGenerator imageCodeGenerator;
//    @Autowired
//    private ValidateCodeGenerator smsCodeGenerator;
//    @Autowired
//    private SmsCodeSender smsCodeSender;

    @Autowired
    private Map<String, ValidateCodeProcessor> validateCodeProcessors;

//    @GetMapping("/code/image")
//    public void createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        ImageCode imageCode = (ImageCode) imageCodeGenerator.generator(new ServletWebRequest(request));
//        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
//        ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
//    }
//
//    @GetMapping("/code/sms")
//    public void createSmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletRequestBindingException {
//        ValidateCode smsCode = smsCodeGenerator.generator(new ServletWebRequest(request));
//        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, smsCode);
//        String phone = ServletRequestUtils.getRequiredStringParameter(request, "phone");
//        smsCodeSender.send(phone, smsCode.getCode());
//    }

    @GetMapping("/code/{type}")
    public void createValidateCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) throws IOException, ServletRequestBindingException {
        validateCodeProcessors.get(type + "CodeProcessor").createValidateCode(new ServletWebRequest(request, response));
    }

}
